<template>
  <basic-layout>
    <custom-navbar title="用户登录" left-show />
    <div class="wrapper">
      <nut-form>
        <nut-form-item label="用户名">
          <nut-input v-model="loginForm.username" class="nut-input-text" placeholder="请输入用户" type="text" />
        </nut-form-item>
        <nut-form-item label="密码">
          <nut-input v-model="loginForm.password" class="nut-input-text" placeholder="请输入密码" type="text" />
        </nut-form-item>
      </nut-form>
      <div class="flex flex-justify-center">
        <nut-button type="primary" @click="userLogin">登录</nut-button>
      </div>

      <div class="flex flex-justify-center mt-[15px]">
        <Button
          class-name="btn-max-w"
          plain
          type="primary"
          open-type="getUserInfo"
          @getUserInfo="getUserInfoEventDetail"
        >
          <IconFont
            class="p-[5px]"
            size="50"
            name=""
          ></IconFont>
        </Button>
      </div>
    </div>
  </basic-layout>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import Taro from '@tarojs/taro';
import { IconFont } from '@nutui/icons-vue-taro';
import { useAuthStore } from '@/store';
import { localStg } from '@/utils';
import { login, wxLogin } from '@/api/auth';
import type { LoginForm, LoginFormVo } from '@/api/auth/type';

const store = useAuthStore();
const loginForm = ref<LoginForm>({
  username: '',
  password: '',
  grantType: '',
  clientId: ''
});

const loginAfter = (res: LoginFormVo | null) => {
  store.token = res?.access_token;
  console.log(store.token);
  localStg.set('token', store.token);
  Taro.switchTab({
    url: '/pages/index/index'
  });
};

const userLogin = async () => {
  const res = await login(loginForm.value);
  loginAfter(res.success);
};

const getUserInfoEventDetail = () => {
  Taro.login({
    async success(res) {
      const data = await wxLogin(res.code);
      loginAfter(data.success);
    }
  });
};

definePageConfig({
  navigationBarTitleText: '用户登录'
});
</script>

<style lang="scss"></style>
